package io.renren.common.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.annotation.SeasonFilter;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.interceptor.DataScope;
import io.renren.common.redis.RedisUtils;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.SysDictDataDao;
import io.renren.modules.sys.entity.SysDictDataEntity;
import io.renren.modules.sys.service.SysDictDataService;
import io.renren.modules.sys.service.SysParamsService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 数据过滤，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class SeasonFilterAspect {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysDictDataDao sysDictDataDao;

    @Pointcut("@annotation(io.renren.common.annotation.SeasonFilter)")
    public void dataFilterCut() {

    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) {
        Object params = point.getArgs()[0];
        if (params != null && params instanceof Map) {
            try {
                //否则进行数据过滤
                Map map = (Map) params;
                String sqlFilter = getSqlFilter(point);
                map.put(Constant.SQL_FILTER, new DataScope(sqlFilter));
            } catch (Exception e) {

            }
            return;
        }
        throw new io.renren.common.exception.RenException(ErrorCode.DATA_SCOPE_PARAMS_ERROR);
    }

    /**
     * 获取数据过滤的SQL
     */
    private String getSqlFilter(JoinPoint point) throws Exception {
        UserDetail user = SecurityUser.getUser();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = point.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
        SeasonFilter seasonFilter = method.getAnnotation(SeasonFilter.class);
        //获取表的别名
        String tableAlias = seasonFilter.tableAlias();
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }
        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        // 从redis中获取season的值
        String season = (String) redisUtils.get("season-" + user.getId());
        // 如果redis中没有，则从数据库中获取
        if (StringUtils.isBlank(season) || "{}".equals(season)) {
            SysDictDataEntity data = sysDictDataDao.selectOne(
                    new QueryWrapper<SysDictDataEntity>()
                            .eq("dict_type_id", "2000")
                            .orderByDesc("sort")
                            .last("limit 1")
            );
            if (data != null) {
                season = data.getDictValue();
                redisUtils.set("season-" + user.getId(), data.getDictValue());
            }else{
                final String DEFAULT_SEASON = "2024";
                season = DEFAULT_SEASON;
                redisUtils.set("season-" + user.getId(), DEFAULT_SEASON);
            }
        }

        sqlFilter.append(tableAlias).append(seasonFilter.season());
        sqlFilter.append(" = ").append(season).append(" ");

        sqlFilter.append(")");
        return sqlFilter.toString();
    }

}
